package ar.com.e2solver.solver.operator.impl;

import ar.com.e2solver.exception.BusinessException;
import ar.com.e2solver.model.Coordinate;
import ar.com.e2solver.model.Puzzle;
import ar.com.e2solver.solver.Individual;
import ar.com.e2solver.solver.RandomConstants;
import ar.com.e2solver.solver.operator.MutationOperator;

public class RowExchangeMutationOperator implements MutationOperator {
	
	private static RowExchangeMutationOperator instance = new RowExchangeMutationOperator();
	
	private RowExchangeMutationOperator(){}
	
	public static RowExchangeMutationOperator getInstance() {
		return instance;
	}

	public Individual operate(Individual individualToMutate) throws BusinessException {
		// Crea una copia del rompecabezas
		Puzzle p = new Puzzle(individualToMutate.getPuzzle());
		
		if(p.getRowsNumber() > 4){
			int row1 = RandomConstants.RANDOM.nextInt(p.getRowsNumber() - 2) + 1;
			int row2 = RandomConstants.RANDOM.nextInt(p.getRowsNumber() - 2) + 1;
			swapRows(p, row1, row2);
		}
		
		return new Individual(p);
	}

	private void swapRows(Puzzle p, int row1, int row2) throws BusinessException {
		Coordinate c1, c2;
		for (int i = 0; i < p.getRowsNumber(); i++) {
			c1 = new Coordinate(row1, i);
			c2 = new Coordinate(row2, i);
			if(p.canSwap(c1, c2)){
				p.swapPositions(c1, c2);
			}
		}
	}

}
